package com.example.runnable;

import com.example.mapper.BasicMapper;
import com.example.utils.TextFileReader;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.example.runnable.Constants.PATH;
import static com.example.runnable.Constants.W_PATH;

@Component
@ConditionalOnProperty(name = "run-env",havingValue = "test01")
public class Test01 implements ApplicationRunner {

    @Resource
    SqlSessionFactory sqlSessionFactory;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        long begin=System.currentTimeMillis();
        TextFileReader fileReader = null;
        try {
            fileReader = new TextFileReader(W_PATH,"utf-8");
            List<String> list=null;
            BasicMapper mapper = sqlSession.getMapper(BasicMapper.class);
            int i=1;
            while (fileReader.hasNext()){
                list = fileReader.readNextLines(200);
                long start = System.currentTimeMillis();
                /*for (String s : list) {
                    s ="'"+s.replace(",", "','")+"'";
                    mapper.insertData(s,"T_BOND_BASIS_INFO","ID,NAME,AGE");
                }*/
                List<String> collect = list.stream().map(s -> "'" + s.replace(",", "','") + "'")
                        .collect(Collectors.toList());
                mapper.insertDataList(collect,"T_BOND_BASIS_INFO","ID,NAME,AGE");
//                if (i%20==0){
//                }
                sqlSession.commit();
                sqlSession.clearCache();
                collect.clear();
                list.clear();
                long end = System.currentTimeMillis();
                System.out.println("总耗时:"+(end-begin)/1000+",耗时:"+(end-start)+";批次:"+(i++)*200);
            }
            System.out.println("耗时:"+(System.currentTimeMillis()-begin));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (fileReader!=null){
                fileReader.close();
            }
            sqlSession.close();
        }
    }
}
